package xiaohuo.fancyring.data

import eos.moe.dragoncore.network.PacketSender
import org.bukkit.entity.ArmorStand
import org.bukkit.entity.EntityType
import org.bukkit.entity.Player
import taboolib.common.platform.function.submit
import taboolib.platform.util.sendLang
import xiaohuo.fancyring.FancyRing
import xiaohuo.fancyring.config.ConfigManager
import xiaohuo.fancyring.util.getHealthPercent
import xiaohuo.fancyring.util.takeStats

class RunningRealBody(private val target: Player, private val realBody: RealBodyData) {
    private val internal: ArmorStand = target.world.spawnEntity(target.location, EntityType.ARMOR_STAND) as ArmorStand

    private var time = 0

    private val task = submit(delay = 20, period = 20) {
        if (time >= realBody.time) {
            target.sendLang("RealBodyOver")
            closeShow()
        } else {
            if (realBody.handleSecondCost(target)) {
                time++
            } else {
                target.sendLang(
                    "SecondRealBodyFail",
                    realBody.secondCostVault,
                    target.getHealthPercent(realBody.secondCostHealth)
                )
                closeShow()
            }
        }
    }

    init {
        internal.isInvulnerable = true
        internal.customName = realBody.customName
    }

    fun closeShow() {
        internal.remove()
        task.cancel()
        target.takeStats(FancyRing::class.java)
    }

    fun showToPlayer(player: Player) {
        PacketSender.sendEntityLocationBind(
            player,
            internal.uniqueId,
            target.uniqueId,
            ConfigManager.realBodyForward,
            ConfigManager.realBodyHeight,
            ConfigManager.realBodySideways,
            true,
            true
        )
    }
}